package com.atguigu.linklist;

public class ReverseBetween {
    public static void main(String[] args) {
        ListNode head=new ListNode(1);
        head.next=new ListNode(2);
        head.next.next=new ListNode(3);
        head.next.next.next=new ListNode(4);
        head.next.next.next.next=new ListNode(5);
        ListNode res=reverseBetween(head,1,5);
        while(res!=null){
            System.out.println(res.val);
            res=res.next;
        }

    }
    public static ListNode reverseBetween(ListNode head,int m,int n){
        if(head==null){
            return null;
        }
        if(head.next==null){
            return head;
        }
        if(n==m){
            return head;
        }
        ListNode dummyHead=new ListNode(-1);
        dummyHead.next=head;
        ListNode pre=dummyHead;
        for(int i=0;i<m-1;i++){
            pre=pre.next;
        }
        ListNode slow=pre.next; //
        ListNode fast=head;
        for(int i=0;i<n-1;i++){
            fast=fast.next;
        }
        ListNode post=head;
        if(fast.next!=null){
            post=fast.next;
        }
        fast.next=null;
        ListNode cur=slow.next;
        slow.next=null;
        while(cur!=null){
            ListNode node=cur.next;
            cur.next=slow;
            slow=cur;
            cur=node;
        }
        //反转成功，进行拼接
        pre.next=slow;
        cur=head;
        while(cur.next!=null){
            cur=cur.next;
        }
        if(post!=head){
            cur.next=post;
        }
        return dummyHead.next;
    }
}
